//
//  WebViewController.m
//  svqj
//
//  Created by xftt on 14-6-25.
//
//

#import "WebViewController.h"
#import "NewWebViewController.h"
#import "Query.h"
#import "QuanJing.h"
#import "FilesDownManage.h"
#import "SortMenuView.h"
#import "MainViewController.h"

@interface WebViewController ()<UIWebViewDelegate>
{
    UIWebView *_vWeb;
    NSMutableDictionary *qjdictionary;
    UIView *vbg;
    UIView *vloading;
}

@end

@implementation WebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithURL:(NSString*)URL
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        self.url = URL;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _vWeb = [[UIWebView alloc] initWithFrame:_contentView.bounds];
    [_contentView addSubview:_vWeb];
    [_vWeb setScalesPageToFit:YES];
    [_vWeb.scrollView setBounces:NO];
    _vWeb.delegate = self;
    [_editButton setHidden:YES];
    
    [_vWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
    
    vbg = [[UIView alloc] initWithFrame:_vWeb.frame];
//    [_contentView addSubview:vbg];
    [vbg setBackgroundColor:[UIColor blackColor]];
    [vbg setAlpha:0.3];
    
    vloading = [[UIView alloc] initWithFrame:CGRectMake(372, 234, 100, 100)];
    [vloading setBackgroundColor:[UIColor colorWithHexString:@"#343434"]];
    vloading.layer.cornerRadius = 15;
//    [_contentView addSubview:vloading];
    
    UIActivityIndicatorView *actv = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(40, 28, 20, 20)];
    [actv setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [actv setHidden:NO];
    [actv startAnimating];
    [vloading addSubview:actv];
    
    UILabel *lbLoading = [[UILabel alloc]initWithFrame:CGRectMake(9, 58, 82, 20)];
    [lbLoading setBackgroundColor:[UIColor clearColor]];
    [lbLoading setTextAlignment:NSTextAlignmentCenter];
    [lbLoading setTextColor:[UIColor colorWithHexString:@"AAAAAA"]];
    [lbLoading setText:@"加载中..."];
    [lbLoading setFont:[UIFont systemFontOfSize:15]];
    [vloading addSubview:lbLoading];
    
}

-(void)reLoadWeb
{
    [_vWeb loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的，原文没有提到。
    [[NSUserDefaults standardUserDefaults] synchronize];
    [vloading setHidden:YES];
    [vbg setHidden:YES];
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeOther ||
        navigationType == UIWebViewNavigationTypeLinkClicked)//点击链接
    {
        NSURL *url = [request URL];
        NSString *query = [url query];
        NSLog(@"url %@ \n %@",url, url.absoluteString);
		if (query && [query rangeOfString:@"openwin=1"].location != NSNotFound)
        {
            [self performSelector:@selector(openURLInNewWebView:) withObject:url.absoluteString afterDelay:0.5];
            return NO;
        }
        NSString *reqURL= [[request URL] absoluteString];
        if ([reqURL hasPrefix:@"svqj://down"]) {
            Query *query = [[Query alloc]initWithURL:reqURL];
            NSString *jid = [query getValue:@"jid"];
            NSString *str = [_vWeb stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById(\"%@\").innerHTML",jid]];
            str = [str stringByReplacingOccurrencesOfString:@"&amp;" withString:@"&"];
            qjdictionary = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil]];
            
            NSUserDefaults *_Data = [NSUserDefaults standardUserDefaults];
            NSArray* QJSort = [_Data objectForKey:@"QJSort"];
            if ([QJSort count]>0) {
                [qjdictionary setObject:@"" forKey:@"sortid"];
                [qjdictionary setObject:@"" forKey:@"sortname"];
                
                SortMenuView *sortMenu = [[SortMenuView alloc]initWithFrame:_contentView.bounds];
                [sortMenu setFController:self];
                [sortMenu setQuanjing:qjdictionary];
                [sortMenu setQJSort:QJSort];
                [_contentView addSubview:sortMenu];
            }
            else
            {
                [self saveSort:qjdictionary from:nil];
            }
            
            return NO;
        }
    }
    
    [vloading setHidden:NO];
    [vbg setHidden:NO];
    
	return YES;
}

- (void)saveSort:(NSDictionary*)qj from:(NSDictionary*)qjing
{
    //下载到本地
    QuanJing *quanj = [[QuanJing alloc]initWithDictionary:qj];
    if (qjdictionary == nil || [quanj.archive length] == 0) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"下载文件异常，请于服务商联系！"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
    else
    {
        [[FilesDownManage sharedFilesDownManage]downFile:quanj];
    }
}

- (void)openURLInNewWebView:(NSString *)url
{
    MainViewController *main = (MainViewController*)self.tabFrameController;
    [main showNewWeb:url];
}

@end
